﻿using System;
using HttpApiGateway.Idempotent;
using HttpApiGateway.Interface;
using RpcCacheClient.Interface;
using RpcClient.Interface;
using RpcHelper;

namespace ApiGateway.Idempotent.Token
{
    [RpcClient.Attr.UnityName("Memcached")]
    [RpcClient.Attr.ClassLifetimeAttr(RpcClient.Attr.ClassLifetimeType.单例)]
    internal class MemcachedTokenService : ITokenIdempotent
    {
        private readonly IIdentityService _Service;
        private readonly IMemcachedCache _Memcached;
        private readonly IIdempotentConfig _Config;
        public MemcachedTokenService(IIdentityService service, IMemcachedCache memcached, IIdempotentConfig config)
        {
            _Memcached = memcached;
            _Config = config;
            _Service = service;
        }
        public StatusSaveType SaveType => StatusSaveType.Memcached;
        public string ApplyToken()
        {
            long token = _Service.CreateId();
            return !_Memcached.Add("Idempotent_" + token, token, new TimeSpan(0, 0, _Config.Expire))
                ? throw new ErrorException("gateway.idempotent.token.apply.fail")
                : token.ToString();
        }

        public void Dispose()
        {
           
        }

        public bool SubmitToken(string tokenId)
        {
            string key = "Idempotent_" + tokenId;
            return _Memcached.Remove(key);
        }
    }
}
